<template>
  <div>
    <div>
      <!-- 树形控件 -->
      <!-- show-checkbox 显示复选框 -->
      <!-- check-strictly 取消父子之间关联 -->
      <el-tree
        ref="tree"
        :data="permissionList"
        :props="defaultProps"
        default-expand-all
        show-checkbox
        check-strictly
        node-key="id"
        @node-click="handleNodeClick"
      />

    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { getRoleById, assignPrem } from '@/api/setting'
import { transTree } from '@/utils'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      permissionList: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  created() {
    this.getPermissionList()
    this.getRoleById()
  },
  methods: {
    // 点击节点触发的事件
    handleNodeClick() {},
    // 获取到角色已有的权限进行回填
    async getRoleById() {
      const res = await getRoleById(this.roleId)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    // 获取到所有的权限列表并转换树形结构
    async getPermissionList() {
      const res = await getPermissionList()
      this.permissionList = transTree(res.data, '0')
    },
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 给角色设置权限按钮--确认按钮
    async setRolesBtn() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPrem({ id: this.roleId, permIds: permIds })
      this.$message.success(res.message)
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
